﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using BuySoftwareOnline.Domain.Abstract;
using BuySoftwareOnline.Domain;

namespace BuySoftwareOnline.Domain.Concrete
{

    public class ProductRepository : IProductRepository
    {
        private BuySoftwareOnlineDataContext context;

        public ProductRepository()
        {
            context = new BuySoftwareOnlineDataContext();
        }

        public IQueryable<Product> Products 
        {
            get { return context.Products; }
        }

        public void SaveProduct(Product product)
        {
            var IsExist = context.Products.Where(p => p.ProductID == product.ProductID);
            if (IsExist.Count() != 0)
            {
                Product realProduct = context.Products.Single(p => p.ProductID == product.ProductID);
                realProduct.ProductID = product.ProductID;
                realProduct.ProductName = product.ProductName;
                realProduct.Description = product.Description;
                realProduct.Content = product.Content;
                realProduct.Requirement = product.Requirement;
                realProduct.Size = product.Size;
                realProduct.PlatForm = product.PlatForm;
                realProduct.UnitPrice = product.UnitPrice;
                realProduct.Total = product.Total;
                realProduct.IsView = product.IsView;
                realProduct.CreateTime = product.CreateTime;
                realProduct.CategoryID = product.CategoryID;
                realProduct.SupplierID = product.SupplierID;
                realProduct.CreateTime = DateTime.Now;
                var arrayFileType = new string[] { "image/jpeg", "image/jpg", "image/png", "image/gif" };
                if (arrayFileType.Contains(product.ScreenShotType))
                    if (product.ScreenShot != null)
                    {
                        realProduct.ScreenShot = product.ScreenShot;
                        realProduct.ScreenShotType = product.ScreenShotType;
                    }
                if (arrayFileType.Contains(product.ImageType))
                    if (product.ImageContent != null)
                    {
                        realProduct.ImageContent = product.ImageContent;
                        realProduct.ImageType = product.ImageType;
                    }
                //context.Products.Attach(product,false);
                //context.Refresh(RefreshMode.KeepCurrentValues,product);
            }
            else
            {
                product.CreateTime = DateTime.Now;
                context.Products.InsertOnSubmit(product);
            }
            context.SubmitChanges();
        }

        public void DeleteProduct(Product product)
        {
            context.Products.DeleteOnSubmit(product);
            context.SubmitChanges();
        }
    }
}
